﻿(function () {
    //通知插件
    var instance = function (params, componentInfo) {
        var self = this;
        //显示通知
        this.Show = function () {
            $('#notify').addClass('open');
        };
        //通知集合
        this.Notifies = ko.observableArray([]);
        //未读通知总数
        this.TotalCount = ko.observable(0);
        //根据时间获取友好性字符串
        this.GetTime = function (time) {
            if (time.indexOf('+08:00') == -1)
                time += '+08:00';
            var date = new Date(time);
            var now = new Date();
            var min = parseInt(Math.abs(now - date) / 1000 / 60);
            if (min <= 1)
                return '刚刚';
            if (min <= 60)
                return min + '分钟前';
            if (min <= 60 * 24)
                return parseInt(min / 60) + '小时前';
            if (min <= 60 * 24 * 30)
                return parseInt(min / 60 / 24) + '天前';
            return "很久以前";
        };
        //移除通知
        this.Remove = function (item) {
            mwc.restApi.delete({
                url: '/api/Site_Notifies/' + item.Id, blockUI: false, success: function () {
                    self.Notifies.remove(item);
                    self.TotalCount(self.TotalCount() - 1);
                }
            });
        };
        //获取并更新总记录数
        this.GetTotalCount = function () {
            mwc.restApi.get({
                url: '/api/Site_Notifies/Unread/Count', blockUI: false, success: function (data) {
                    self.TotalCount(data.TotalCount);
                }
            });
        };
        //初始化
        this.Init = function () {
            var notifyHubProxy = $.connection.notifyHub;
            //接收通知（注意，务必在连接前定义）
            notifyHubProxy.client.Notify = function (notify) {
                console.debug(notify);
                if (typeof (notify.length) != 'undefined') {
                    self.Notifies(notify);
                } else {
                    var arr = self.Notifies();
                    var hasExist = false;
                    $.each(arr, function (i, v) {
                        if (v.Id == notify.Id) {
                            arr.splice(i, 1, notify)
                            hasExist = true;
                            return;
                        }
                    });
                    console.debug('hasExist:', hasExist);
                    if (!hasExist) {
                        arr.push(notify);
                        if (arr.length > 8)
                            arr.splice(7, 1)
                    }
                    self.Notifies(arr.sort(function (left, right) {
                        return left.UpdateTime < right.UpdateTime ? 1 : -1;
                    }));
                    self.Show();
                    //console.debug(self.Notifies());
                }
                self.GetTotalCount();
            };
            $.connection.hub.start().done(function () {
                //console.debug('已成功连接服务器！');
            }).fail(function () {
                //console.log('连接失败！'); 
            });
        };
        self.Init();
    };
    var notifyViewModelInstance = {
        createViewModel: function (params, componentInfo) {
            return new instance(params, componentInfo);
        }
    };
    //按钮组选择组件
    ko.components.register("notify",
    {
        viewModel: notifyViewModelInstance,
        template: "<li class=\"dropdown\" id=\"notify\">" +
                    "<a class=\"dropdown-toggle count-info\" data-toggle=\"dropdown\" href=\"#\" aria-expanded=\"true\">" +
                        "<i class=\"fa fa-bell\"></i>  <span class=\"label label-primary\" data-bind=\"text:TotalCount\">0</span>" +
                    "</a><div class=\"dropdown-backdrop\"></div>" +
                    "<ul class=\"dropdown-menu dropdown-alerts\">" +
                        "<!-- ko foreach:Notifies -->" +
                        "<li>" +
                            "<a data-bind=\"attr:{href:typeof(Href)=='undefined'?'':Href}\">" +
                                "<div>" +
                                    "<i class=\"fa fa-envelope fa-fw\" data-bind=\"css:typeof(IconCls)=='undefined'?'':IconCls\"></i> <label data-bind=\"text:Title\"></label>" +
                                    "<span class=\"pull-right text-muted small\" data-bind=\"text:$parent.GetTime(UpdateTime)\">刚刚</span>&nbsp;&nbsp;<i class=\"fa fa-times\" data-bind=\"click:$parent.Remove\"></i>" +
                                "</div>" +
                                "<div data-bind=\"text:Message\">" +
                                "</div>" +
                                "<!-- ko if: TaskPercentage>0 -->" +
                                "<div class=\"progress progress-mini\">" +
                                    "<div data-bind=\"style:{width:TaskPercentage+'%'}\" class=\"progress-bar\"></div>" +
                                "</div>" +
                                "<!-- /ko -->" +
                            "</a>" +
                        "</li>" +
                        "<li class=\"divider\"></li>" +
                        "<!-- /ko -->" +
                        "<li>" +
                            "<div class=\"text-center link-block\">" +
                                "<a href=\"/Site_Notify\">" +
                                    "<strong>查看所有通知&nbsp;&nbsp;<i class=\"fa fa-angle-right\"></i></strong>" +
                                "</a>" +
                            "</div>" +
                        "</li>" +
                    "</ul>" +
                "</li>"
    });
})();